package com.simon.study.algorithm.bank;

/**
 * <p>
 *
 * @author simon
 * @date 2022/7/4 1:59 下午
 */
public class Leetcode07 {

    public static void main(String[] args) {
        int b = 1200;
        System.out.println(reverse2(b));
    }

    public static int reverse(int x){
        int f = 0x80000000, t = 0, s = 0;
        if( x < 0 ){ x = ~x + 1; s = 1; }

        String xs = x + "";

        char[] schs = xs.toCharArray();
        
        if(xs.length() < 10){
            for(int i=0; i<schs.length; i++){
                t = (t<<3) + (t<<1);
                t = t + (schs[schs.length-i-1]-'0');
            }
        }else if( xs.length() == 10){
            for(int i=0; i<schs.length; i++){
                int tmp = t<<1;
                for(int j=0; j<3 && t>0; j++) {
                    if ((f & (t = t << 1)) != 0) {
                        return 0;
                    }
                }

                int ft = Integer.MAX_VALUE - t - tmp;
                if(ft < 0){ return 0; }
                t =t + tmp + (schs[schs.length-i-1]-'0');
            }
        }

        return s == 0 ? t : (t != 0 ? ~t+1 : 0);
    }


    public static int reverse2(int x){
        int t = 0, s = 0, tmp, last;
        if( x < 0 ){ x = ~x + 1; s = 1; }

        while (x != 0){
            last = x % 10;

            tmp = t;
            t = (t << 3) + (t << 1);

            if( t/10 != tmp ){ return 0; }

            t = t + last;
            x = x/10;
        }

        return s == 0 ? t : (t != 0 ? ~t+1 : 0);
    }
}
